let datas = [
    {
        text:"中国",
        link:'#'
    },
    {
        text:"中华",
        link:'#'
    },
    {
        text:"中产",
        link:'#'
    },
    {
        text:"中国人",
        link:'#'
    },
    {
        text:"中国人民",
        link:'#'
    },
    {
        text:"中国人寿",
        link:'#'
    },
    {
        text:"中国人民大学",
        link:'#'
    },
    {
        text:"中国人民共和国",
        link:'#'
    },
    {
        text:"中国移动",
        link:'#'
    },
    {
        text:"中国联通",
        link:'#'
    },
    {
        text:"中国消防",
        link:'#'
    },
    {
        text:"中国移动办卡",
        link:'#'
    },
    {
        text:"中国",
        link:'#'
    },
    {
        text:"中国体育",
        link:'#'
    },
    {
        text:"中国体育彩票",
        link:'#'
    }
];

let $ = (sel) => document.querySelector(sel);
let ipt = $('.ipt'),
    val,
    list = $('.list'),
    index = -1;

ipt.addEventListener('input',() => {
    let newDatas = [];
    val = ipt.value;
    datas.forEach((data,idx) => {
        if(data.text.indexOf(val) === 0){
            newDatas.push(data);
        }
    });
    if(newDatas.length === 0) return;
    list.classList.add('show');
    list.innerHTML = newDatas.map((data,idx) => {
        return '<li data-id="'+ idx +'"><a href="'+ data.link +'">' + data.text + '</a></li>';
    }).join('');
});

// 滑过li的时候高亮显示
list.addEventListener('mouseover',(e) => {
    let target = e.target;
    if(target.nodeName === 'A'){
        index = target.parentNode.getAttribute('data-id');
        showActive();
    }
});

list.addEventListener('click',(e) => {
    let target = e.srcElement;
    if(target.nodeName === 'A'){
        ipt.value = target.innerHTML;
        index = -1;
    }
})

// 按上下方向键的时候切换高亮
document.addEventListener('keydown',(e) => { 
    let key = e.keyCode;
    let len = list.children.length;
    console.log(key);
    if(key === 40){
        index++;
        if(index >= len) index = 0;
        showActive();
    }else if(key === 38){
        index--;
        if(index < 0) index = len - 1;
        showActive();
    }else if(key === 13){
        ipt.value = $('.active').firstElementChild.innerHTML;
        list.classList.remove('show');
        index = -1;
    }
});

// 显示高亮
function showActive(){
    let lis = [...list.children],
        cur = $('.active');
    cur && cur.classList.remove('active');
    lis[index].classList.add('active');
    // 将文本框的值设为高亮的li的文本
    ipt.value = lis[index].firstElementChild.innerHTML;
}
// 在页面空白处点击，隐藏菜单
document.body.addEventListener('click',() => {
    list.classList.remove('show');
});
   